'''
组件增加tooltip提示信息，hover时显示提示信息
'''
import tkinter as tk
from tkinter import ttk


class ToolTip:
    def __init__(self, widget, text):
        self.widget = widget
        self.text = text
        self.tipwindow = None
        self.id = None
        self.x = self.y = 0
        # 绑定鼠标进入和离开事件
        widget.bind("<Enter>", self.enter)
        widget.bind("<Leave>", self.leave)

    def enter(self, event=None):
        # 延迟显示提示信息
        self.schedule()

    def leave(self, event=None):
        # 取消显示提示信息
        self.unschedule()
        # 隐藏提示窗口
        self.hidetip()

    def schedule(self):
        # 取消之前的延迟任务
        self.unschedule()
        # 设置延迟 500 毫秒后显示提示信息
        self.id = self.widget.after(500, self.showtip)

    def unschedule(self):
        # 取消延迟任务
        id = self.id
        self.id = None
        if id:
            self.widget.after_cancel(id)

    def showtip(self):
        # 获取鼠标位置
        x = self.widget.winfo_pointerx() + 20
        y = self.widget.winfo_pointery() + 10
        # 创建提示窗口
        self.tipwindow = tw = tk.Toplevel(self.widget)
        tw.wm_overrideredirect(True)
        tw.wm_geometry(f"+{x}+{y}")
        # 创建标签显示提示信息
        label = tk.Label(tw, text=self.text, justify=tk.LEFT,
                         background="#ffffe0", relief=tk.SOLID, borderwidth=1,
                         font=("tahoma", "8", "normal"))
        label.pack(ipadx=1)

    def hidetip(self):
        # 隐藏提示窗口
        tw = self.tipwindow
        self.tipwindow = None
        if tw:
            tw.destroy()


# 示例使用
def runner():
    root = tk.Tk()
    # 创建按钮
    button = ttk.Button(root, text="悬停查看提示")
    button.pack(pady=20)
    # 创建工具提示
    ToolTip(button, "这是一个按钮的提示信息")
    root.mainloop()


if __name__ == "__main__":
    runner()
